Scopes

  • Only one entity can exist with a particular name in a particular scope.

Scopes

#include <iostream>

int main () {
    int x = 10;
    int y = 20;
    {
        int x;   // ok, inner scope.
        x = 50;  // sets value to inner x
        y = 50;  // sets value to (outer) y
        std::cout << "inner block:\n";
        std::cout << "x: " << x << '\n';
        std::cout << "y: " << y << '\n';
    }
    std::cout << "outer block:\n";
    std::cout << "x: " << x << '\n';
    std::cout << "y: " << y << '\n';
    return 0;
}
  • prints

inner block:
x: 50
y: 50
outer block:
x: 10
y: 50

Namespaces

  • Syntax:

    namespace identifier {
    named_entities
    }
    
  • Non-local names bring more possibilities for name collision, especially considering that libraries may declare many functions, types, and variables, neither of them local in nature, and some of them very generic.

  • Namespaces allow us to group named entities that otherwise would have global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names.

  • Example:

    #include <iostream>
    
    namespace foo {
        int value() { return 5; }
    }
    
    namespace bar {
        const double pi = 3.1416;
        double value() { return 2*pi; }
    }
    
    int main () {
        cout << foo::value() << '\n';
        cout << bar::value() << '\n';
        cout << bar::pi << '\n';
        return 0;
    }
    

The std namespace

  • All  the entities (variables, types, constants, and functions) of the standard C++ library are declared within the std namespace.

using

  • The keyword using introduces a name into the current declarative region (such as a block), thus avoiding the need to qualify the name.

#include <iostream>
using namespace std;

namespace first {
    int x = 5;
    int y = 10;
}

namespace second {
    double x = 3.1416;
    double y = 2.7183;
}

int main () {
    {
        using first::x;
        cout << x << '\n';
        cout << first:y << '\n';
    }
    {
        using namespace second;
        cout << x << '\n';
        cout << y << '\n';
    }
    return 0;
}
Aliasing
  • Syntax:

namespace new_name = current_name;